package cfca.seal.web.tag;

import cfca.sadk.util.CertUtil;
import cfca.sadk.x509.certificate.X509Cert;
import cfca.seal.bean.Seal;
import cfca.seal.bean.SealCert;
import cfca.seal.dao.main.ISealCertDao;
import cfca.seal.dao.main.ISealDao;
import cfca.seal.system.Env;
import cfca.seal.util.EncryptUtil;
import cfca.seal.util.SealCertUtil;
import cfca.seal.util.TimeUtil;
import cfca.seal.web.tag.base.TemplateDirectiveModelBase;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;

@Component
public class ValidateFlagNameTag extends TemplateDirectiveModelBase
{

  @Resource
  ISealDao sealDao;

  @Resource
  private ISealCertDao sealCertDao;

  public String process(Environment env, Map paramsMap, TemplateModel[] loopVars, TemplateDirectiveBody body)
    throws TemplateException, IOException
  {
    StringBuffer sf = new StringBuffer();
    if ((this.elementValue != null) && (!this.elementValue.isEmpty())) {
      try {
        Seal seal = this.sealDao.getSealById(this.elementValue);
        X509Cert x509Cert = null;
        if (0 == seal.getCertType()) {
          if (SealCertUtil.isSM2(seal.getSealPfxData()))
            x509Cert = CertUtil.getCertFromSM2(seal.getSealPfxData());
          else
            x509Cert = CertUtil.getCertFromPFX(seal.getSealPfxData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
        }
        else if ((2 == seal.getCertType()) || (1 == seal.getCertType())) {
          SealCert sealCert = this.sealCertDao.getSealCertById(seal.getSealCertId());
          x509Cert = new X509Cert(sealCert.getPublickCertData());
        }

        if (null != x509Cert) {
          Date current = new Date();
          if (current.after(x509Cert.getNotAfter())) {
            sf.append("<font color='red'>已经到期</font>");
          } else {
            long day = Long.valueOf(Env.overdueDays).longValue() + 1L;

            if (null != x509Cert) {
              Date notAfter = x509Cert.getNotAfter();
              Date today = TimeUtil.getCurrentTime();
              day = (notAfter.getTime() - today.getTime()) / 86400000L;
            }

            if ((day >= 0L) && (day <= Long.valueOf(Env.overdueDays).longValue()))
              sf.append("<font color='red'>即将到期</font>");
          }
        }
        else {
          sf.append("");
        }
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    return sf.append("").toString();
  }
}